﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

using SampleFramework;
using SlimDX;
using SlimDX.Direct3D9;
using starpillage.Input;
using starpillage.Rendering.Terrain;
using starpillage.Python;

namespace starpillage
{
    public class Starpillage : Game
    {
        public static Color BackgroundColor = Color.Bisque;

        const int InitialWidth = 800;
        const int InitialHeight = 600;

        Camera camera = new Camera();
        Keyboard keyboard = new Keyboard();
        TextConsole console = new TextConsole();

        public Camera Camera { get { return camera; } }
        public Keyboard Keyboard { get { return keyboard; } }
        public TextConsole Console { get { return console; } }

        PythonHost pythonHost = new PythonHost();
        Sprite fontSprite;
        SlimDX.Direct3D9.Font levelFont;

        public Device Device
        {
            get { return GraphicsDeviceManager.Direct3D9.Device; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Asteroids"/> class.
        /// </summary>
        public Starpillage()
        {
            Window.ClientSize = new Size(InitialWidth, InitialHeight);
            Window.Text = "Starpillage";

            keyboard.SetKeyEventHandlers(Window);
            keyboard.RegisterKeyAction(Keys.Escape, t => Exit());
            //keyboard.RegisterKeyAction(Keys.F1, t => GraphicsDeviceManager.ToggleFullScreen());
            keyboard.RegisterKeyAction(Keys.Back, t => RunInitScript());

            camera.FieldOfView = (float)(Math.PI / 2);
            camera.NearPlane = 1.0f;
            camera.FarPlane = 1000.0f;
            camera.Location = new Vector3(-30.0f, -30.0f, -30.0f);
            camera.Target = new Vector3(128.0f, 128.0f, 0.0f);

            DeviceSettings settings = new DeviceSettings();
            settings.BackBufferWidth = InitialWidth;
            settings.BackBufferHeight = InitialHeight;
            settings.DeviceVersion = DeviceVersion.Direct3D9;
            settings.Windowed = true;
#if DEBUG
            settings.EnableVSync = false;
#else
        settings.EnableVSync = true;
#endif
            settings.MultisampleType = MultisampleType.EightSamples;

            Resources.Add(console);

            GraphicsDeviceManager.ChangeDevice(settings);

            HeightmapMesh terrainMesh = new HeightmapMesh(256, 256, (x, y) => 10 * (float)Math.Sin(0.1f * x + Math.Cos(0.1f * y)));
            Resources.Add(terrainMesh);
            Components.Add(terrainMesh);
        }

        protected override void Initialize()
        {
            base.Initialize();

            fontSprite = new Sprite(Device);
            levelFont = new SlimDX.Direct3D9.Font(Device, 40, 0, FontWeight.Bold, 0, false, CharacterSet.Default,
                Precision.Default, FontQuality.ClearTypeNatural, PitchAndFamily.DontCare, "");

            pythonHost.SetVariable("game", this);
            RunInitScript();
        }

        protected void RunInitScript()
        {
            pythonHost.Run(@"Python\init.py");
        }

        protected override void LoadContent()
        {
            base.LoadContent();

            camera.AspectRatio = (float)Window.Width / Window.Height;

            float halfHeight = (float)Math.Abs(Math.Tan(camera.FieldOfView / 2) * camera.Location.Z);
            float halfWidth = halfHeight * camera.AspectRatio;

            fontSprite.OnResetDevice();
            levelFont.OnResetDevice();
        }

        protected override void UnloadContent()
        {
            base.UnloadContent();

            fontSprite.OnLostDevice();
            levelFont.OnLostDevice();
        }

        protected override void Dispose(bool disposing)
        {
            fontSprite.Dispose();
            levelFont.Dispose();

            base.Dispose(disposing);
        }

        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            keyboard.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, BackgroundColor, 1.0f, 0);
            Device.BeginScene();

            Device.SetTransform(TransformState.World, Matrix.Identity);
            Device.SetTransform(TransformState.View, camera.ViewMatrix);
            Device.SetTransform(TransformState.Projection, camera.ProjectionMatrix);

            base.Draw(gameTime);

            Device.EndScene();
        }
    }
}
